package com.tangkun.environment.utils;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.media.ExifInterface;
import android.media.ThumbnailUtils;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.GridView;
import android.widget.ListAdapter;
import android.widget.ListView;

import com.alibaba.fastjson.JSON;
import com.tangkun.environment.R;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.net.URL;
import java.net.URLConnection;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import cn.qqtheme.framework.entity.City;
import cn.qqtheme.framework.entity.County;
import cn.qqtheme.framework.entity.Province;
import cn.qqtheme.framework.util.ConvertUtils;
import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Func1;


@SuppressWarnings("deprecation")
public class Utils {

    public static String changePriceStyle(String s) {
        if (Utils.isEmpty(s)) {
            return "";
        } else if (!Utils.isNum(s)) {
            return s;
        } else if (s.contains(".")) {
            DecimalFormat formater = new DecimalFormat(",##0.00");
            return formater.format(Double.parseDouble(s)).toString();
        } else {
            DecimalFormat formater = new DecimalFormat(",##0");
            return formater.format(Double.parseDouble(s)).toString();
        }
    }

    private static String changeStrToPrice(String str1) {
        str1 = new StringBuilder(str1).reverse().toString();     //先将字符串颠倒顺序
        String str2 = "";
        for (int i = 0; i < str1.length(); i++) {
            if (i * 3 + 3 > str1.length()) {
                str2 += str1.substring(i * 3, str1.length());
                break;
            }
            str2 += str1.substring(i * 3, i * 3 + 3) + ",";
        }
        if (str2.endsWith(",")) {
            str2 = str2.substring(0, str2.length() - 1);
        }
        //最后再将顺序反转过来  
        return new StringBuilder(str2).reverse().toString();
    }

    public static boolean isEmpty(String s) {
        if (null == s)
            return true;
        if (s.length() == 0)
            return true;
        if (s.trim().length() == 0)
            return true;
        if ("null".equals(s)) {
            return true;
        }
        return false;
    }

    /**
     * 点击某一控件隐藏软件盘的方法
     */
    public static void hideSoftKeyboard(Activity activity, View view) {
        InputMethodManager imm = (InputMethodManager) activity
                .getSystemService(Activity.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
    }

    /**
     * 点击某一控件显示软件盘的方法
     */
    public static void showSoftKeyboard(Activity activity, View view) {
        try {
            InputMethodManager imm = (InputMethodManager) activity
                    .getSystemService(Activity.INPUT_METHOD_SERVICE);
            imm.showSoftInput(view, 0);
        } catch (Exception e) {
            // TODO: handle exception
        }
    }

    /**
     * 将流转成字节数组
     *
     * @param is
     * @return
     * @throws IOException
     */
    public static byte[] stream2Bytes(InputStream is) throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int length = 0;
        while ((length = is.read(buffer, 0, 1024)) != -1) {
            baos.write(buffer, 0, length);
        }
        baos.flush();
        return baos.toByteArray();
    }

    /**
     * 根据URL得到图片
     */
    public static Bitmap getBitmapFromUrl(String urlStr) throws Exception {
        URL url = new URL(urlStr);
        URLConnection connection = url.openConnection();
        connection.connect();
        InputStream inputStream = connection.getInputStream();
        BufferedInputStream bis = new BufferedInputStream(inputStream);
        Bitmap bitmap = BitmapFactory.decodeStream(bis);
        bis.close();
        inputStream.close();
        return bitmap;
    }

    /**
     * 保存文件到指定路径，后缀名不修改
     */
    public static void saveImageToSD(Bitmap bitmap, String path, String fileName) {
        File dir = new File(path);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        File imageFile = new File(path + fileName);
        FileOutputStream fileOutputStream = null;
        try {
            fileOutputStream = new FileOutputStream(imageFile);
            BufferedOutputStream bos = new BufferedOutputStream(
                    fileOutputStream);
            if (bitmap != null) {
                bitmap.compress(CompressFormat.PNG, 100, bos);
                bos.flush();
                bos.close();
            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fileOutputStream != null) {
                try {
                    fileOutputStream.close();
                } catch (IOException e) {

                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 检查手机号是否正确
     *
     * @param phoneNumber 手机号码
     * @return
     */
    public static boolean isTruePhone(String phoneNumber) {
        if (phoneNumber == null || "".equals(phoneNumber)) {
            return false;
        }
        Pattern p = Pattern.compile("^(1[1-9])\\d{9}$");
        Matcher m = p.matcher(phoneNumber);
        if (m.matches()) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 判断邮箱格式是否正确
     *
     * @param emailAddress
     * @return
     */
    public static boolean isTrueEmail(String emailAddress) {
        if (emailAddress == null || "".equals(emailAddress)) {
            return false;
        }
        String strPattern = "^[a-zA-Z0-9][ \\w\\.-]*[a-zA-Z0-9]@[a-zA-Z0-9][\\w\\.-]*[a-zA-Z0-9]\\.[a-zA-Z][a-zA-Z\\.]*[a-zA-Z]$";

        // 利用了Java里面的正则表达式
        Pattern p = Pattern.compile(strPattern);
        Matcher m = p.matcher(emailAddress);
        // 当目标string与传入的string完全匹配，返回true,否则返回false
        return m.matches();
    }

    /**
     * 判断密码格式是否正确
     *
     * @param passwordStr
     * @return
     */
    public static boolean isPassword(String passwordStr) {
        // TODO Auto-generated method stub
        if (passwordStr == null || "".equals(passwordStr)) {
            return false;
        }
        String strPattern = "^[\\w.]{6,20}$";

        // 利用了Java里面的正则表达式
        Pattern p = Pattern.compile(strPattern);
        Matcher m = p.matcher(passwordStr);
        // 当目标string与传入的string完全匹配，返回true,否则返回false
        return m.matches();
    }

    public static boolean isNum(String str) {
        if (str == null || "".equals(str)) {
            return false;
        }
        if (str.equals("")) {
            return false;
        }
        return str.matches("^[-+]?(([0-9]+)([.]([0-9]+))?|([.]([0-9]+))?)$");
    }

    /**
     * 获取SDCard根路径
     */
    public static String getSDCardPath() {
        String path = "";
        if (Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED)) {
            path = Environment.getExternalStorageDirectory().getAbsolutePath()
                    + "/Tommy/image/";
            File file = new File(path);
            if (!file.exists()) {
                file.mkdirs();
            }
        }
        return path;
    }

    /**
     * 获取路径中的文件名
     */
    public static String getFileNameFromURL(String url) {
        String fileName = url.substring(url.lastIndexOf("/") + 1);
        return fileName;
    }

    /**
     * 绘制Gallery亮点
     *
     * @param num
     * @param position
     * @param context
     * @param normalPoint
     * @param selectedPoint
     * @param spaceWidth
     * @return
     */
    public static Bitmap drawPoint(int num, int position, Context context,
                                   int normalPoint, int selectedPoint, int spaceWidth) {
        Bitmap normal = ((BitmapDrawable) context.getResources().getDrawable(
                normalPoint)).getBitmap();
        Bitmap select = ((BitmapDrawable) context.getResources().getDrawable(
                selectedPoint)).getBitmap();
        Bitmap bitmap = Bitmap.createBitmap((num + 2) * spaceWidth,
                spaceWidth / 2, Bitmap.Config.ARGB_8888);

        Canvas mPointsCanvas = new Canvas();
        mPointsCanvas.setBitmap(bitmap);
        int x = spaceWidth;
        for (int i = 0; i < num; i++) {
            if (i == position) {
                mPointsCanvas.drawBitmap(select, x, 0, null);
            } else {
                mPointsCanvas.drawBitmap(normal, x, 0, null);
            }
            x += spaceWidth;
        }
        return bitmap;
    }

    /**
     * 隐藏键盘
     */
    public static void hideKeybord(Activity activity) {
        try {
            ((InputMethodManager) activity
                    .getSystemService(activity.INPUT_METHOD_SERVICE))
                    .hideSoftInputFromWindow(activity.getCurrentFocus()
                                    .getWindowToken(),
                            InputMethodManager.HIDE_NOT_ALWAYS);
        } catch (Exception e) {

        }
    }

    /**
     * 获取版本名
     */
    public static String getVersionName(Activity activity) {
        String versionName = "1.0.0";
        try {
            PackageInfo info = activity.getPackageManager().getPackageInfo(
                    activity.getPackageName(), 0);
            // 当前应用的版本名称
            versionName = info.versionName;
        } catch (NameNotFoundException e) {
            e.printStackTrace();
        }
        return versionName;
    }

    /**
     * 获取版本号
     */
    public static int getVersionCode(Activity activity) {
        int versionCode = 100;
        try {
            PackageInfo info = activity.getPackageManager().getPackageInfo(
                    activity.getPackageName(), 0);
            // 当前应用的版本号
            versionCode = info.versionCode;
        } catch (NameNotFoundException e) {
            e.printStackTrace();
        }
        return versionCode;
    }

    public static final int COMPRESS_QUALITY = 100;

    public static int getImageSize(Bitmap bmp) {
        try {
            if (bmp == null) {
                return 0;
            }
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            bmp.compress(CompressFormat.PNG, COMPRESS_QUALITY, baos);
            int size = baos.size();
            baos.flush();
            baos.close();
            return size;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return 0;
    }

    public static String getImgUrl(Context context, String imgUrl) {
        SharedPreferences pref = context.getSharedPreferences("SaveImg",
                Context.MODE_APPEND);
        return pref.getString(imgUrl, "false");
    }

    public static void insertImgUrl(Context context, String imgUrl) {
        SharedPreferences pref = context.getSharedPreferences("SaveImg",
                Context.MODE_APPEND);
        Editor editor = pref.edit();
        editor.putString(imgUrl, "true");
        editor.commit();
    }

    /**
     * 引导页判断
     */
    public static void setLand(Context context, boolean bool) {
        SharedPreferences pref = context.getSharedPreferences("GuidePage",
                Context.MODE_APPEND);
        Editor editor = pref.edit();
        editor.putBoolean("TAG", bool);
        editor.commit();
    }

    public static boolean getLand(Context context) {
        SharedPreferences pref = context.getSharedPreferences("GuidePage",
                Context.MODE_PRIVATE);
        return pref.getBoolean("TAG", false);
    }

    public static String getImgHtml(String imgUrl) {
        String imgHtml = "";
        String imgHtmlHead = "<!DOCTYPE html><html><head><meta charset='utf-8' /><meta name='viewport' content='width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no' /><title>img</title></head><body style='padding:0; margin:0;'><img src='";
        String imgHtmlEnd = "' style='width:100%;' /></body></html>";
        imgHtml = imgHtmlHead + imgUrl + imgHtmlEnd;
        return imgHtml;
    }

    /**
     * 柔化效果(高斯模糊)(优化后比上面快三倍)
     *
     * @param bmp
     * @return
     */
    public static Bitmap blurImageAmeliorate(Bitmap bmp) {
        // 高斯矩阵
        int[] gauss = new int[]{1, 2, 1, 2, 4, 2, 1, 2, 1};

        int width = bmp.getWidth();
        int height = bmp.getHeight();
        Bitmap bitmap = Bitmap.createBitmap(width, height,
                Bitmap.Config.RGB_565);

        int pixR = 0;
        int pixG = 0;
        int pixB = 0;

        int pixColor = 0;

        int newR = 0;
        int newG = 0;
        int newB = 0;

        int delta = 20; // 值越小图片会越亮，越大则越暗

        int idx = 0;
        int[] pixels = new int[width * height];
        bmp.getPixels(pixels, 0, width, 0, 0, width, height);
        for (int i = 1, length = height - 1; i < length; i++) {
            for (int k = 1, len = width - 1; k < len; k++) {
                idx = 0;
                for (int m = -1; m <= 1; m++) {
                    for (int n = -1; n <= 1; n++) {
                        pixColor = pixels[(i + m) * width + k + n];
                        pixR = Color.red(pixColor);
                        pixG = Color.green(pixColor);
                        pixB = Color.blue(pixColor);

                        newR = newR + (int) (pixR * gauss[idx]);
                        newG = newG + (int) (pixG * gauss[idx]);
                        newB = newB + (int) (pixB * gauss[idx]);
                        idx++;
                    }
                }

                newR /= delta;
                newG /= delta;
                newB /= delta;

                newR = Math.min(255, Math.max(0, newR));
                newG = Math.min(255, Math.max(0, newG));
                newB = Math.min(255, Math.max(0, newB));

                pixels[i * width + k] = Color.argb(255, newR, newG, newB);

                newR = 0;
                newG = 0;
                newB = 0;
            }
        }
        bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
        return bitmap;
    }

    public static Bitmap BoxBlurFilter(Bitmap bmp) {
        /** 水平方向模糊度 */
        float hRadius = 5;
        /** 竖直方向模糊度 */
        float vRadius = 5;
        /** 模糊迭代度 */
        int iterations = 3;
        int width = bmp.getWidth();
        int height = bmp.getHeight();
        int[] inPixels = new int[width * height];
        int[] outPixels = new int[width * height];
        Bitmap bitmap = Bitmap.createBitmap(width, height,
                Bitmap.Config.ARGB_8888);
        bmp.getPixels(inPixels, 0, width, 0, 0, width, height);
        for (int i = 0; i < iterations; i++) {
            blur(inPixels, outPixels, width, height, hRadius);
            blur(outPixels, inPixels, height, width, vRadius);
        }
        blurFractional(inPixels, outPixels, width, height, hRadius);
        blurFractional(outPixels, inPixels, height, width, vRadius);
        bitmap.setPixels(inPixels, 0, width, 0, 0, width, height);
        return bitmap;
    }

    public static Drawable BoxBlurFilter(Bitmap bmp, int blurX, int blurY, int blurDegreee) {
        /** 水平方向模糊度 */
        float hRadius = blurX;
        /** 竖直方向模糊度 */
        float vRadius = blurY;
        /** 模糊迭代度 */
        int iterations = blurDegreee;
        int width = bmp.getWidth();
        int height = bmp.getHeight();
        int[] inPixels = new int[width * height];
        int[] outPixels = new int[width * height];
        Bitmap bitmap = Bitmap.createBitmap(width, height,
                Bitmap.Config.ARGB_8888);
        bmp.getPixels(inPixels, 0, width, 0, 0, width, height);
        for (int i = 0; i < iterations; i++) {
            blur(inPixels, outPixels, width, height, hRadius);
            blur(outPixels, inPixels, height, width, vRadius);
        }
        blurFractional(inPixels, outPixels, width, height, hRadius);
        blurFractional(outPixels, inPixels, height, width, vRadius);
        bitmap.setPixels(inPixels, 0, width, 0, 0, width, height);
        Drawable drawable = new BitmapDrawable(bitmap);
        return drawable;
    }

    public static void blur(int[] in, int[] out, int width, int height,
                            float radius) {
        int widthMinus1 = width - 1;
        int r = (int) radius;
        int tableSize = 2 * r + 1;
        int divide[] = new int[256 * tableSize];

        for (int i = 0; i < 256 * tableSize; i++)
            divide[i] = i / tableSize;

        int inIndex = 0;

        for (int y = 0; y < height; y++) {
            int outIndex = y;
            int ta = 0, tr = 0, tg = 0, tb = 0;

            for (int i = -r; i <= r; i++) {
                int rgb = in[inIndex + clamp(i, 0, width - 1)];
                ta += (rgb >> 24) & 0xff;
                tr += (rgb >> 16) & 0xff;
                tg += (rgb >> 8) & 0xff;
                tb += rgb & 0xff;
            }

            for (int x = 0; x < width; x++) {
                out[outIndex] = (divide[ta] << 24) | (divide[tr] << 16)
                        | (divide[tg] << 8) | divide[tb];

                int i1 = x + r + 1;
                if (i1 > widthMinus1)
                    i1 = widthMinus1;
                int i2 = x - r;
                if (i2 < 0)
                    i2 = 0;
                int rgb1 = in[inIndex + i1];
                int rgb2 = in[inIndex + i2];

                ta += ((rgb1 >> 24) & 0xff) - ((rgb2 >> 24) & 0xff);
                tr += ((rgb1 & 0xff0000) - (rgb2 & 0xff0000)) >> 16;
                tg += ((rgb1 & 0xff00) - (rgb2 & 0xff00)) >> 8;
                tb += (rgb1 & 0xff) - (rgb2 & 0xff);
                outIndex += height;
            }
            inIndex += width;
        }
    }

    public static void blurFractional(int[] in, int[] out, int width,
                                      int height, float radius) {
        radius -= (int) radius;
        float f = 1.0f / (1 + 2 * radius);
        int inIndex = 0;

        for (int y = 0; y < height; y++) {
            int outIndex = y;

            out[outIndex] = in[0];
            outIndex += height;
            for (int x = 1; x < width - 1; x++) {
                int i = inIndex + x;
                int rgb1 = in[i - 1];
                int rgb2 = in[i];
                int rgb3 = in[i + 1];

                int a1 = (rgb1 >> 24) & 0xff;
                int r1 = (rgb1 >> 16) & 0xff;
                int g1 = (rgb1 >> 8) & 0xff;
                int b1 = rgb1 & 0xff;
                int a2 = (rgb2 >> 24) & 0xff;
                int r2 = (rgb2 >> 16) & 0xff;
                int g2 = (rgb2 >> 8) & 0xff;
                int b2 = rgb2 & 0xff;
                int a3 = (rgb3 >> 24) & 0xff;
                int r3 = (rgb3 >> 16) & 0xff;
                int g3 = (rgb3 >> 8) & 0xff;
                int b3 = rgb3 & 0xff;
                a1 = a2 + (int) ((a1 + a3) * radius);
                r1 = r2 + (int) ((r1 + r3) * radius);
                g1 = g2 + (int) ((g1 + g3) * radius);
                b1 = b2 + (int) ((b1 + b3) * radius);
                a1 *= f;
                r1 *= f;
                g1 *= f;
                b1 *= f;
                out[outIndex] = (a1 << 24) | (r1 << 16) | (g1 << 8) | b1;
                outIndex += height;
            }
            out[outIndex] = in[width - 1];
            inIndex += width;
        }
    }

    public static int clamp(int x, int a, int b) {
        return (x < a) ? a : (x > b) ? b : x;
    }

    /**
     * 按正方形裁切图片
     */
    public static Bitmap imageCrop(Bitmap bitmap, int width, int height) {

        int startX = 0;
        int startY = 0;

        int bw = bitmap.getWidth();
        int bh = bitmap.getHeight();

        float w = bitmap.getWidth(); // 得到图片的宽，高
        float h = bitmap.getHeight();

        float f1 = w / h;
        float f2 = width * 1.0f / height;

        if (f1 > f2) {
            w = (int) (h / height * width);
            startX = (int) (bw - w) / 2;
        } else {
            h = (int) (w / width * height);
            startY = (int) (bh - h) / 2;
        }

        //下面这句是关键
        bitmap = Bitmap.createBitmap(bitmap, startX, startY, (int) w, (int) h, null, false);
        return bitmap;
    }

    public static final int MEDIA_TYPE_IMAGE = 1;
    public static final int MEDIA_TYPE_VIDEO = 2;

    @SuppressLint("NewApi")
    public static String getPath(Activity context, Uri uri) {
        final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
        // DocumentProvider
        if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
            // ExternalStorageProvider
            if (isExternalStorageDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];
                if ("primary".equalsIgnoreCase(type)) {
                    return Environment.getExternalStorageDirectory() + "/"
                            + split[1];
                }
            }
            // DownloadsProvider
            else if (isDownloadsDocument(uri)) {
                final String id = DocumentsContract.getDocumentId(uri);
                final Uri contentUri = ContentUris.withAppendedId(
                        Uri.parse("content://downloads/public_downloads"),
                        Long.valueOf(id));
                return getDataColumn(context, contentUri, null, null);
            }
            // MediaProvider
            else if (isMediaDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];
                Uri contentUri = null;
                if ("image".equals(type)) {
                    contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                } else if ("video".equals(type)) {
                    contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                } else if ("audio".equals(type)) {
                    contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                }
                final String selection = "_id=?";
                final String[] selectionArgs = new String[]{split[1]};
                return getDataColumn(context, contentUri, selection,
                        selectionArgs);
            }
        } else {
            return getImageInformation(context, uri)[0];
        }
        return null;
    }

    public static String getDataColumn(Context context, Uri uri,
                                       String selection, String[] selectionArgs) {
        Cursor cursor = null;
        final String column = "_data";
        final String[] projection = {column};
        try {
            cursor = context.getContentResolver().query(uri, projection,
                    selection, selectionArgs, null);
            if (cursor != null && cursor.moveToFirst()) {
                final int index = cursor.getColumnIndexOrThrow(column);
                return cursor.getString(index);
            }
        } finally {
            if (cursor != null)
                cursor.close();
        }
        return null;
    }

    /**
     * 获取图片路径和角度
     *
     * @param cxt
     * @param mImageCaptureUri
     * @return
     */
    public static String[] getImageInformation(Activity cxt,
                                               Uri mImageCaptureUri) {
        String[] results = new String[2];
        // 不管是拍照还是选择图片每张图片都有在数据中存储也存储有对应旋转角度orientation值
        // 所以我们在取出图片是把角度值取出以便能正确的显示图片,没有旋转时的效果观看
        ContentResolver cr = cxt.getContentResolver();
        if (mImageCaptureUri == null) {
            return results;
        }
        Cursor cursor = cr.query(mImageCaptureUri, null, null, null, null);// 根据Uri从数据库中找
        if (cursor != null) {
            cursor.moveToFirst();// 把游标移动到首位，因为这里的Uri是包含ID的所以是唯一的不需要循环找指向第一个就是了
            String filePath = cursor.getString(cursor.getColumnIndex("_data"));// 获取图片路
            results[0] = filePath;
            String orientation = cursor.getString(cursor
                    .getColumnIndex("orientation"));// 获取旋转的角度
            results[1] = orientation;
            cursor.close();
        } else {
            results[0] = mImageCaptureUri.getPath();
            results[1] = String.valueOf(readPictureDegree(results[0]));
        }
        return results;
    }

    /**
     * 读取图片属性：旋转的角度
     *
     * @param path 图片绝对路径
     * @return degree旋转的角度
     */
    public static int readPictureDegree(String path) {
        int degree = 0;
        try {
            ExifInterface exifInterface = new ExifInterface(path);
            int orientation = exifInterface.getAttributeInt(
                    ExifInterface.TAG_ORIENTATION,
                    ExifInterface.ORIENTATION_NORMAL);
            switch (orientation) {
                case ExifInterface.ORIENTATION_ROTATE_90:
                    degree = 90;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_180:
                    degree = 180;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_270:
                    degree = 270;
                    break;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return degree;
    }

    public static Uri getOutputMediaFileUri(int type) {
        File file = getOutputMediaFile(type);
        if (file == null) {
            return null;
        }
        return Uri.fromFile(file);
    }

    public static File getOutputMediaFile(int type) {
        if (!isSDState()) {
            return null;
        }
        File mediaStoreaDir = new File(
                Environment.getExternalStorageDirectory(), "hotelggenterprise");
        if (!mediaStoreaDir.exists()) {
            if (!mediaStoreaDir.mkdirs()) {
                return null;
            }
        }
        File mediaFile;
        if (type == MEDIA_TYPE_IMAGE) {
            mediaFile = new File(mediaStoreaDir.getPath() + File.separator
                    + "IMG_TEMP" + ".jpg");
        } else if (type == MEDIA_TYPE_VIDEO) {
            mediaFile = new File(mediaStoreaDir.getPath() + File.separator
                    + "VID_TIMP" + ".mp4");
        } else {
            return null;
        }
        if (mediaFile.exists()) {
            try {
                mediaFile.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return mediaFile;
    }

    /**
     * 判断sd是否可写
     *
     * @return
     */
    public static boolean isSDState() {
        boolean sdCardExist = Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED); // 判断sd卡是否存在
        return sdCardExist;
    }

    public static boolean isExternalStorageDocument(Uri uri) {
        return "com.android.externalstorage.documents".equals(uri
                .getAuthority());
    }

    public static boolean isDownloadsDocument(Uri uri) {
        return "com.android.providers.downloads.documents".equals(uri
                .getAuthority());
    }

    public static boolean isMediaDocument(Uri uri) {
        return "com.android.providers.media.documents".equals(uri
                .getAuthority());
    }

    public static int px2dp(Context context, float pxValue) {
        float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale);
    }

    public static int dp2px(Context context, float dpValue) {
        float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    /**
     * 动态测量listview Item的高度
     */
    public static void setListViewHeight(ListView listView) {
        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter == null) {
            return;
        }
        int totalHeight = 0;
        for (int i = 0; i < listAdapter.getCount(); i++) {
            View listItem = listAdapter.getView(i, null, listView);
            listItem.measure(0, 0);
            totalHeight += listItem.getMeasuredHeight();
        }
        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
        listView.setLayoutParams(params);
    }


    /**
     * bitmap 转化成 file文件
     *
     * @param context
     * @param bitmap
     * @return file
     */
    public static String bitmapToFile(Context context, Bitmap bitmap,
                                      int quality) {
        String fileName = String.valueOf(System.currentTimeMillis()) + ".jpg";
        // create a file to write bitmap data
        File file = new File(Environment.getExternalStorageDirectory() + "/EnvironmentApp/" + fileName);
//        File file = new File(fileName);
        // Convert bitmap to byte array
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        bitmap.compress(CompressFormat.JPEG, quality /* ignored for JPEG */, bos);
        byte[] bitmapdata = bos.toByteArray();
        // write the bytes in file
        FileOutputStream fos;
        try {
            if (file.exists()) {
                file.delete();
            }
            file.createNewFile();
            fos = new FileOutputStream(file);
            fos.write(bitmapdata);
            fos.close();
            if (bitmap != null) {
                bitmap.recycle();
                bitmap = null;
            }
            return file.getAbsolutePath();
        } catch (FileNotFoundException e2) {
            e2.printStackTrace();
        } catch (IOException e3) {
            e3.printStackTrace();
        }
        return null;
    }

    /**
     * 生成二维码Bitmap
     *
     * @param content   内容
     * @param widthPix  图片宽度
     * @param heightPix 图片高度
     * @param logoBm    二维码中心的Logo图标（可以为null）
     * @param filePath  用于存储二维码图片的文件路径
     * @return 生成二维码及保存文件是否成功
     */
    public static boolean createQRImage(String content, int widthPix, int heightPix, Bitmap logoBm, String filePath) {
        try {
            if (content == null || "".equals(content)) {
                return false;
            }

            //配置参数
            Map<EncodeHintType, Object> hints = new HashMap<>();
            hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
            //容错级别
            hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
            //设置空白边距的宽度
            hints.put(EncodeHintType.MARGIN, 0); //default is 4

            // 图像数据转换，使用了矩阵转换
            BitMatrix bitMatrix = new QRCodeWriter().encode(content, BarcodeFormat.QR_CODE, widthPix, heightPix, hints);
//            bitMatrix = deleteWhite(bitMatrix);//删除白边
            int[] pixels = new int[widthPix * heightPix];
            // 下面这里按照二维码的算法，逐个生成二维码的图片，
            // 两个for循环是图片横列扫描的结果
            for (int y = 0; y < heightPix; y++) {
                for (int x = 0; x < widthPix; x++) {
                    if (bitMatrix.get(x, y)) {
                        pixels[y * widthPix + x] = 0xff000000;
                    } else {
                        pixels[y * widthPix + x] = 0xffffffff;
                    }
                }
            }

            // 生成二维码图片的格式，使用ARGB_8888
            Bitmap bitmap = Bitmap.createBitmap(widthPix, heightPix, Bitmap.Config.ARGB_8888);
            bitmap.setPixels(pixels, 0, widthPix, 0, 0, widthPix, heightPix);

            if (logoBm != null) {
                bitmap = addLogo(bitmap, logoBm);
            }

            //必须使用compress方法将bitmap保存到文件中再进行读取。直接返回的bitmap是没有任何压缩的，内存消耗巨大！
            return bitmap != null && bitmap.compress(Bitmap.CompressFormat.JPEG, 100, new FileOutputStream(filePath));
        } catch (WriterException | IOException e) {
            e.printStackTrace();
        }

        return false;
    }

    /**
     * 删除白边
     *
     * @param matrix
     * @return
     */
    private static BitMatrix deleteWhite(BitMatrix matrix) {
        int[] rec = matrix.getEnclosingRectangle();
        int resWidth = rec[2] + 1;
        int resHeight = rec[3] + 1;

        BitMatrix resMatrix = new BitMatrix(resWidth, resHeight);
        resMatrix.clear();
        for (int i = 0; i < resWidth; i++) {
            for (int j = 0; j < resHeight; j++) {
                if (matrix.get(i + rec[0], j + rec[1]))
                    resMatrix.set(i, j);
            }
        }
        return resMatrix;
    }

    /**
     * 在二维码中间添加Logo图案
     */
    private static Bitmap addLogo(Bitmap src, Bitmap logo) {
        if (src == null) {
            return null;
        }

        if (logo == null) {
            return src;
        }

        //获取图片的宽高
        int srcWidth = src.getWidth();
        int srcHeight = src.getHeight();
        int logoWidth = logo.getWidth();
        int logoHeight = logo.getHeight();

        if (srcWidth == 0 || srcHeight == 0) {
            return null;
        }

        if (logoWidth == 0 || logoHeight == 0) {
            return src;
        }

        //logo大小为二维码整体大小的1/5
        float scaleFactor = srcWidth * 1.0f / 5 / logoWidth;
        Bitmap bitmap = Bitmap.createBitmap(srcWidth, srcHeight, Bitmap.Config.ARGB_8888);
        try {
            Canvas canvas = new Canvas(bitmap);
            canvas.drawBitmap(src, 0, 0, null);
            canvas.scale(scaleFactor, scaleFactor, srcWidth / 2, srcHeight / 2);
            canvas.drawBitmap(logo, (srcWidth - logoWidth) / 2, (srcHeight - logoHeight) / 2, null);

            canvas.save(Canvas.ALL_SAVE_FLAG);
            canvas.restore();
        } catch (Exception e) {
            bitmap = null;
            e.getStackTrace();
        }

        return bitmap;
    }

    /**
     * 文件存储根目录
     */
    public static String getFileRoot(Context context) {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            File external = context.getExternalFilesDir(null);
            if (external != null) {
                return external.getAbsolutePath();
            }
        }
        return context.getFilesDir().getAbsolutePath();
    }

    /**
     * 返回app文件目录
     *
     * @param context
     * @return
     */
    public static String getAppFilePath(Context context) {
        String appPath = getFileRoot(context) + File.separator + "CDKCloudApp";
        File file = new File(appPath);
        if (!file.exists()) {
            file.mkdirs();//创建文件夹
        }
        return appPath;
    }

    /**
     * 获取现在时间 年月日时分秒
     *
     * @return返回字符串格式 yyyy-MM-dd HH:mm:ss
     */
    public static String getCurrentDateWithHms() {
        Date currentTime = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateString = formatter.format(currentTime);
        return dateString;
    }

    /**
     * 获取现在时间 年月日
     *
     * @return 返回短时间字符串格式yyyy-MM-dd
     */
    public static String getCurrentDate() {
        Date currentTime = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        String dateString = formatter.format(currentTime);
        return dateString;
    }

    /**
     * 获取现在时间 年
     *
     * @return 返回短时间字符串格式yyyy
     */
    public static String getCurrentDateYear() {
        Date currentTime = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy");
        String dateString = formatter.format(currentTime);
        return dateString;
    }

    /**
     * 获取现在时间 月
     *
     * @return 返回短时间字符串格式MM
     */
    public static String getCurrentDateMonth() {
        Date currentTime = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("MM");
        String dateString = formatter.format(currentTime);
        return dateString;
    }

    /**
     * 获取现在时间 日
     *
     * @return 返回短时间字符串格式dd
     */
    public static String getCurrentDateDay() {
        Date currentTime = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("dd");
        String dateString = formatter.format(currentTime);
        return dateString;
    }

    /**
     * @param dateString 当前日期 如：2000-01-02
     * @param beforeDay  往前推多少天 如：1
     * @return 当前日期前多少天日期 如：2000-01-01
     */
    public static String getBeforeDate(String dateString, int beforeDay) {
        //字符串转Date
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Date date = null;
        try {
            date = format.parse(dateString);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        //通过Calendar计算
        Calendar calendar = new GregorianCalendar();
        calendar.setTime(date);
        calendar.add(calendar.DATE, -beforeDay);//把日期往后增加一天.整数往后推,负数往前移动
        date = calendar.getTime(); //这个时间就是日期往后推多少天的结果
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        //返回的日期
        String resultDateString = formatter.format(date);
        return resultDateString;
    }

    /**
     * 保留小数点后1位
     * 如果保留的小数点是以.0结尾，则取整数
     *
     * @param msg 初始数据  如：4.2222转换成4.2  4.0000转换成4  4.5555转换成4.6
     */
    public static String getOneDecimalPoint(String msg) {
        if (TextUtils.isEmpty(msg)) {
            return "";
        } else {
            BigDecimal bigDecimal = new BigDecimal(msg);
            // 进位处理，2.35变成2.4
            msg = bigDecimal.setScale(1, BigDecimal.ROUND_HALF_UP) + "";
            // 如果是以.0结尾，则去掉.0取整数
            if (msg.contains(".0")) {
                msg = msg.replace(".0", "");
            }
            return msg;
        }
    }

    /**
     * 保留小数点后1位
     * 如果保留的小数点是以.0结尾，则取整数
     *
     * @param d 初始数据  如：4.2222转换成4.2  4.0000转换成4  4.5555转换成4.6
     */
    public static String getOneDecimalPoint(double d) {
        String msg = String.valueOf(d);
        BigDecimal bigDecimal = new BigDecimal(msg);
        // 进位处理，2.35变成2.4
        msg = bigDecimal.setScale(1, BigDecimal.ROUND_HALF_UP) + "";
        // 如果是以.0结尾，则去掉.0取整数
        if (msg.contains(".0")) {
            msg = msg.replace(".0", "");
        }
        return msg;
    }

    /**
     * 将字符串日期转换成年月日时分
     *
     * @param date 初始数据  如：2017-05-17 12:30:23 转换成 2017-05-17 12:30
     */
    public static String getDateYearMonthDayHourMinute(String date) {
        String result = "";
        if (TextUtils.isEmpty(date)) {
            return result;
        }
        if (date.length() >= 16) {
            result = date.substring(0, 16);//截取年月日时分
            return result;
        }
        return result;
    }

    /**
     * 将字符串日期转换成年月日
     *
     * @param date 初始数据  如：2017-05-17 12:30:23 转换成 2017-05-17
     */
    public static String getDateYearMonthDay(String date) {
        String result = "";
        if (TextUtils.isEmpty(date)) {
            return result;
        }
        if (date.length() >= 10) {
            result = date.substring(0, 10);//截取年月日
            return result;
        }
        return result;
    }

    /**
     * 将字符串日期转换成时分
     *
     * @param date 初始数据  如：2017-05-17 12:30:23 转换成 12:30
     */
    public static String getDateHourMinute(String date) {
        String result = "";
        if (TextUtils.isEmpty(date)) {
            return result;
        }
        if (date.length() >= 16) {
            result = date.substring(11, 16);//截取年月日
            return result;
        }
        return result;
    }

    /**
     * 将字符串日期转换成年月
     *
     * @param date 初始数据  如：2017-05-17 12:30:23 转换成 2017-05
     */
    public static String getDateYearMonth(String date) {
        String result = "";
        if (TextUtils.isEmpty(date)) {
            return result;
        }
        if (date.length() >= 7) {
            result = date.substring(0, 7);//截取年月
            return result;
        }
        return result;
    }

    /**
     * 将字符串日期转换成月日时分
     *
     * @param date 初始数据  如：2017-05-17 12:30:23 转换成 05-17 12:30
     */
    public static String getDateMonthDayHourMinute(String date) {
        String result = "";
        if (TextUtils.isEmpty(date)) {
            return result;
        }
        if (date.length() >= 16) {
            result = date.substring(5, 16);//截取月日时分
            return result;
        }
        return result;
    }

    /**
     * RxJava实现验证码计数问题
     *
     * @param time
     * @return
     */
    public static Observable<Integer> countDown(int time) {
        if (time < 0) time = 0;

        final int countTime = time;
        return Observable.interval(0, 1, TimeUnit.SECONDS)
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .map(new Func1<Long, Integer>() {
                    @Override
                    public Integer call(Long increaseTime) {
                        return countTime - increaseTime.intValue();
                    }
                })
                .take(countTime + 1);
    }

    /**
     * @param dateString 如：2017-03-27 14:12:39
     * @return 日期字符串转时间戳
     */
    public static long dateToTimeStamp(String dateString) {
        if (TextUtils.isEmpty(dateString)) {
            return 0l;
        }
        //Date或者String转化为时间戳
        try {
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date date = format.parse(dateString);
            return date.getTime();
        } catch (Exception e) {
            return 0l;
        }
    }

    /**
     * 温馨提示dialog，不处理确定/取消按钮事件
     */
    public static void showDialogNoClick(final Activity context,
                                         String content, DialogInterface.OnClickListener confirm,
                                         DialogInterface.OnClickListener cancle) {

        AlertDialog.Builder dialog = DialogUtils.getAlertDialog(context);
        dialog.setIcon(new BitmapDrawable());
        dialog.setTitle(R.string.dialog_title);
        dialog.setMessage(content);
        dialog.setCancelable(false);
        dialog.setPositiveButton(R.string.dialog_confirm, confirm);
        dialog.setNegativeButton(R.string.dialog_cancel, cancle);
        dialog.show();
    }

    /**
     * 温馨提示dialog，不处理确定/取消按钮事件
     */
    public static void showDialogNoClick(final Activity context,
                                         String content, String leftString, String rightString,
                                         DialogInterface.OnClickListener confirm,
                                         DialogInterface.OnClickListener cancle) {

        AlertDialog.Builder dialog = DialogUtils.getAlertDialog(context);
        dialog.setIcon(new BitmapDrawable());
        dialog.setTitle(R.string.dialog_title);
        dialog.setMessage(content);
        dialog.setCancelable(false);
        dialog.setPositiveButton(leftString, confirm);
        dialog.setNegativeButton(rightString, cancle);
        dialog.show();
    }

    /**
     * 温馨提示dialog，不处理确定按钮事件
     */
    public static void showDialogNoConfirmClick(final Activity context,
                                                String content, DialogInterface.OnClickListener onClickListener) {
        AlertDialog.Builder dialog = DialogUtils.getAlertDialog(context);
        dialog.setIcon(new BitmapDrawable());
        dialog.setTitle(R.string.dialog_title);
        dialog.setMessage(content);
        dialog.setCancelable(false);
        dialog.setPositiveButton(R.string.dialog_confirm, onClickListener);
        dialog.show();
    }

    /**
     * 温馨提示dialog，提示用户正确信息,结束当前页面（只有确定按钮）
     */
    public static void showDialogFinish(final Activity context, String content) {

        AlertDialog.Builder dialog = DialogUtils.getAlertDialog(context);
        dialog.setIcon(new BitmapDrawable());
        dialog.setTitle(R.string.dialog_title);
        dialog.setMessage(content);
        dialog.setCancelable(false);
        dialog.setPositiveButton(R.string.dialog_confirm,
                new DialogInterface.OnClickListener() {

                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        context.finish();
                    }
                });
        dialog.show();
    }

    /**
     * @param areaCode 县的code
     * @param context  上下文
     * @return 用户住址 省市县
     */
    public static String getAddress(final Context context, int areaCode) {
        String address = "";//结果 省市县 地址
        String proviceName = "";//省
        String cityName = "";//市
        String countyName = "";//县
        try {
            ArrayList<Province> provinceList = new ArrayList<Province>();
            String json = ConvertUtils.toString(context.getAssets().open("city.json"));
            provinceList.addAll(JSON.parseArray(json, Province.class));
            if (provinceList != null) {
                for (int i = 0; i < provinceList.size(); i++) {
                    proviceName = provinceList.get(i).getAreaName();//省名称
                    LogUtils.e("proviceName:" + proviceName);
                    List<City> cityList = provinceList.get(i).getCities();
                    if (cityList != null) {
                        for (int j = 0; j < cityList.size(); j++) {
                            cityName = cityList.get(j).getAreaName();//市名称
                            LogUtils.e("cityName:" + cityName);
                            List<County> countyList = cityList.get(j).getCounties();
                            if (countyList != null) {
                                for (int k = 0; k < countyList.size(); k++) {
                                    if (countyList.get(k).getAreaId().equals(String.valueOf(areaCode))) {
                                        countyName = countyList.get(k).getAreaName();//县名称
                                        LogUtils.e("countyName:" + countyName);
                                        address = proviceName + " " + cityName + " " + countyName;//省市县拼接起来
                                        return address;
                                    }
                                }
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            LogUtils.e("Session getUserAddress() Exception:" + e.toString());
        }
        return address;
    }


    public static void setListViewHeightBasedOnChildren(ListView listView) {
        if (listView == null)
            return;

        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter == null) {
            // pre-condition
            return;
        }

        int totalHeight = 0;
        for (int i = 0; i < listAdapter.getCount(); i++) {
            View listItem = listAdapter.getView(i, null, listView);
            listItem.measure(0, 0);
            totalHeight += listItem.getMeasuredHeight();
        }

        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
        listView.setLayoutParams(params);
    }

    public static void setGrowListViewHeightBasedOnChildren(ListView listView) {
        if (listView == null)
            return;

        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter == null) {
            // pre-condition
            return;
        }

        int totalHeight = 0;
        for (int i = 0; i < listAdapter.getCount(); i++) {
            View listItem = listAdapter.getView(i, null, listView);
            listItem.measure(0, 0);
            totalHeight += listItem.getMeasuredHeight();
        }

        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight + (5 * (listAdapter.getCount() - 1));
        listView.setLayoutParams(params);
    }

    public static void setGridViewHeightBasedOnChildren(GridView gridView, int numColumns) {
        // 获取GridView对应的Adapter
        ListAdapter listAdapter = gridView.getAdapter();
        if (listAdapter == null) {
            return;
        }
        int rows;
        int horizontalBorderHeight = 0;
        Class<?> clazz = gridView.getClass();
        try {
            // 利用反射，取得每行显示的个数
            Field column = clazz.getDeclaredField("mRequestedNumColumns");
            column.setAccessible(true);
            numColumns = (Integer) column.get(gridView);
            // 利用反射，取得横向分割线高度
            Field horizontalSpacing = clazz.getDeclaredField("mRequestedHorizontalSpacing");
            horizontalSpacing.setAccessible(true);
            horizontalBorderHeight = (Integer) horizontalSpacing.get(gridView);
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 判断数据总数除以每行个数是否整除。不能整除代表有多余，需要加一行
        if (listAdapter.getCount() % numColumns > 0) {
            rows = listAdapter.getCount() / numColumns + 1;
        } else {
            rows = listAdapter.getCount() / numColumns;
        }
        int totalHeight = 0;
        for (int i = 0; i < rows; i++) { // 只计算每项高度*行数
            View listItem = listAdapter.getView(i, null, gridView);
            listItem.measure(0, 0); // 计算子项View 的宽高
            totalHeight += listItem.getMeasuredHeight(); // 统计所有子项的总高度
        }
        ViewGroup.LayoutParams params = gridView.getLayoutParams();

        int height = totalHeight + horizontalBorderHeight * (rows - 1);// 最后加上分割线总高度
        params.height = height;

        gridView.setLayoutParams(params);
    }

    /**
     * 获取到距离
     *
     * @param distance 距离 如：6525.693499537469 单位是m
     */
    public static String getDistance(String distance) {
        if (TextUtils.isEmpty(distance)) {
            return "km";
        }
        double distanceDouble = Double.valueOf(getOneDecimalPoint(distance));
        if (distanceDouble > 1000) {
            distanceDouble = distanceDouble / 1000;
            return getOneDecimalPoint(distanceDouble) + "km";
        } else {
            return getOneDecimalPoint(distance) + "m";
        }
    }

    /**
     * 获取图片大小，返回单位MB或KB两种单位
     */
    @SuppressWarnings("resource")
    public static String getImgFileListSizes(List<File> fileList) throws Exception {
        if (fileList.size() <= 0) {
            return "0.00KB";
        }
        long fileSizeLong = 0;
        for (int i = 0; i < fileList.size(); i++) {
            if (fileList.get(i).exists()) {
                FileInputStream fis = null;
                fis = new FileInputStream(fileList.get(i));
                fileSizeLong += fis.available();
            } else {
                fileList.get(i).createNewFile();
                LogUtils.e("UIUtils.java getImgFileSizes():" + "文件不存在");
            }
        }
        DecimalFormat df = new DecimalFormat("#.00");
        if (fileSizeLong < 1048576) {
            return df.format((double) fileSizeLong / 1024) + "KB";
        } else if (fileSizeLong < 1073741824) {
            return df.format((double) fileSizeLong / 1048576) + "MB";
        }
        return "0.00KB";
    }

    /**
     * 获取图片大小，返回单位MB或KB两种单位
     */
    @SuppressWarnings("resource")
    public static String getImgFileSizes(File file) throws Exception {
        long fileSizeLong = 0;
        if (file.exists()) {
            FileInputStream fis = null;
            fis = new FileInputStream(file);
            fileSizeLong += fis.available();
        } else {
            file.createNewFile();
            LogUtils.e("UIUtils.java getImgFileSizes():" + "文件不存在");
        }
        DecimalFormat df = new DecimalFormat("#.00");
        if (fileSizeLong < 1048576) {
            return df.format((double) fileSizeLong / 1024) + "KB";
        } else if (fileSizeLong < 1073741824) {
            return df.format((double) fileSizeLong / 1048576) + "MB";
        }
        return "0.00KB";
    }

    /**
     * 根据 路径 得到 file 得到 bitmap
     *
     * @param filePath
     * @return
     * @throws IOException
     */
    public static Bitmap decodeFile(String filePath) throws IOException {
        Bitmap b = null;
        int IMAGE_MAX_SIZE = 600;

        File f = new File(filePath);
        if (f == null) {
            return null;
        }
        //Decode image size
        BitmapFactory.Options o = new BitmapFactory.Options();
        o.inJustDecodeBounds = true;

        FileInputStream fis = new FileInputStream(f);
        BitmapFactory.decodeStream(fis, null, o);
        fis.close();

        int scale = 1;
        if (o.outHeight > IMAGE_MAX_SIZE || o.outWidth > IMAGE_MAX_SIZE) {
            scale = (int) Math.pow(2, (int) Math.round(Math.log(IMAGE_MAX_SIZE / (double) Math.max(o.outHeight, o.outWidth)) / Math.log(0.5)));
        }

        //Decode with inSampleSize
        BitmapFactory.Options o2 = new BitmapFactory.Options();
        o2.inSampleSize = scale;
        fis = new FileInputStream(f);
        b = BitmapFactory.decodeStream(fis, null, o2);
        fis.close();
        return b;
    }

    /**
     * 获取某年某月的最后一天
     *
     * @param year
     * @param month
     * @return
     */
    public static String getLastDayOfMonth(int year, int month) {
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.YEAR, year);
        cal.set(Calendar.MONTH, month - 1);
        cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DATE));
        return new SimpleDateFormat("yyyy-MM-dd ").format(cal.getTime());
    }

    /**
     * 获取某年某月的第一天
     *
     * @param year
     * @param month
     * @return
     */
    public static String getFirstDayOfMonth(int year, int month) {
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.YEAR, year);
        cal.set(Calendar.MONTH, month - 1);
        cal.set(Calendar.DAY_OF_MONTH, cal.getMinimum(Calendar.DATE));
        return new SimpleDateFormat("yyyy-MM-dd ").format(cal.getTime());
    }

    /**
     * 根据指定的图像路径和大小来获取缩略图 此方法有两点好处： 1.
     * 使用较小的内存空间，第一次获取的bitmap实际上为null，只是为了读取宽度和高度，
     * 第二次读取的bitmap是根据比例压缩过的图像，第三次读取的bitmap是所要的缩略图。 2.
     * 缩略图对于原图像来讲没有拉伸，这里使用了2.2版本的新工具ThumbnailUtils，使 用这个工具生成的图像不会被拉伸。
     *
     * @param imagePath 图像的路径
     * @param width     指定输出图像的宽度
     * @param height    指定输出图像的高度
     * @return 生成的缩略图
     */
    public static Bitmap getImageThumbnail(String imagePath, int width, int height) {
        Bitmap bitmap = null;
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        // 获取这个图片的宽和高，注意此处的bitmap为null
        bitmap = BitmapFactory.decodeFile(imagePath, options);
        options.inJustDecodeBounds = false; // 设为 false
        // 计算缩放比
        int h = options.outHeight;
        int w = options.outWidth;
        int beWidth = w / width;
        int beHeight = h / height;
        int be = 1;
        if (beWidth < beHeight) {
            be = beWidth;
        } else {
            be = beHeight;
        }
        if (be <= 0) {
            be = 1;
        }
        options.inSampleSize = be;
        // 重新读入图片，读取缩放后的bitmap，注意这次要把options.inJustDecodeBounds 设为 false
        bitmap = BitmapFactory.decodeFile(imagePath, options);
        // 利用ThumbnailUtils来创建缩略图，这里要指定要缩放哪个Bitmap对象
        bitmap = ThumbnailUtils.extractThumbnail(bitmap, width, height, ThumbnailUtils.OPTIONS_RECYCLE_INPUT);
        return bitmap;
    }
}
